-- UIWorkshopConfig
-- Create by zouyb
-- 工匠配置界面

-- 工坊总数
local totalNum = 9;

-- 显示出来的工坊总数
local showtotalNum = totalNum;

-- 每种材料可以分配的工匠上限
local WorkerLimit = 100;

require "game/ui/form/workshop/UIWorkshopDesc"

-- 工人名称
local workerNames;

--UIWorkshopConfig继承自Layer
UIWorkshopConfig = class("UIWorkshopConfig", function()
    return cc.Layer:create();
end);

function UIWorkshopConfig.create(areaId)
    return UIWorkshopConfig.new(areaId);
end

local resize;

--构造函数
function UIWorkshopConfig:ctor(areaId)
    self:setName("UIWorkshopConfig");

    self.areaId = areaId;

    local ress = DungeonAreaM.getOpenResource();
    showtotalNum = #ress + 1;

    workerNames = { getLocStr("gold_worker"), getLocStr("iron_worker"),
        getLocStr("crystal_worker"), getLocStr("steel_worker"),
        getLocStr("soul_worker"), getLocStr("silver_worker"),
        getLocStr("arcance_worker"), getLocStr("au_worker"),
        getLocStr("holy_worker"), getLocStr("talent_fruit_worker"),  };

    --初始化
    local node = cc.CSLoader:createNode("layout/workshop/WorkshopConfig.csb");
    self:addChild(node);
    self.node = node;

    -- 设置标题样式
    local titleLabel = findChildByName(node, "TOP/title_bg/text");
    titleLabel:setString(getLocStr("workshop_config"));
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 当前工坊工人配置
    local workshop = AlchemyWorkshopM.getWorkshop();
    self.config = {};
    for i = 1, totalNum do
        self.config[i] = workshop[i];
    end

    -- 当前的空闲工人数
    self.idleWorkerNum = AlchemyWorkshopM.getIdleWorkerNum();

    -- 工人总数
    self.totalWorkerNum = AlchemyWorkshopM.getTotalWorkerNum();

    resize(self);

    self:init();

    -- 注册返回按钮点击事件
    local btnOK = findChildByName(self.node, "BT/ok");
    local function onOKClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 先处理工人减少的情况
            local oldConfig = AlchemyWorkshopM.getWorkshop();
            for i = 1, totalNum do
                local curNum = self.config[i];
                local oldNum = oldConfig[i];

                if oldNum > curNum then
                    AlchemyWorkshopM.subWorkerNum(i, oldNum - curNum);
                end
            end

            -- 再处理工人增加的情况
            local oldConfig = AlchemyWorkshopM.getWorkshop();
            for i = 1, totalNum do
                local curNum = self.config[i];
                local oldNum = oldConfig[i];

                if curNum > oldNum then
                    AlchemyWorkshopM.addWorkerNum(i, curNum - oldNum);
                end
            end

            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIWorkshopConfig");
        end
    end
    AddTouchEventListener(btnOK, onOKClick);
    if AlchemyWorkshopM.isAllGuideFinished() then
        AddBackEventHandler(self, btnOK, btnOK.touchEventListener);
    end
    TextStyleM.setTextStyle(btnOK, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOK:setTitleText(getLocStr("btn_text_ok"));

    -- 注册说明点击事件
    local btnDesc= findChildByName(self.node, "BT/desc");
    local function onDescClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_caption");
            local uiDesc = UIWorkshopDesc.create();
            UIMgr:getCurrentScene():addForm(uiDesc);
        end
    end
    btnDesc:addTouchEventListener(onDescClick);
    TextStyleM.setTextStyle(btnDesc, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnDesc:setTitleText(getLocStr("btn_text_help"));

    -- 注册事件
    EventMgr.register("UIWorkshopConfig", event.ITEM_COUNT_UPDATED, function()
        self:updateAllCount();
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:resumeEffect();
                uiForm:showUIElem();
            end
            EventMgr.removeAll("UIWorkshopConfig");
        elseif ev == "enter" then
            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:hideUnneccesElem();
            end
        end
    end);
end

-- 配置界面
function UIWorkshopConfig:init()
    local scrollview = findChildByName(self.node, "TOP/scrollview");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/workshop/WorkshopItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    --左边距
    local leftMargin = 305;

    --行间距
    local gap = 15;

    local widgetHeight = 104;
    local startHeight = (widgetHeight + gap) / 2;

    --计算总高度
    local totalHeight = math.max(showtotalNum * (widgetHeight + gap), scrollview:getInnerContainerSize().height);
    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height - totalHeight;
    end

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    local ress = DungeonAreaM.getOpenResource();
    self.workshopChildren = {};
    self.items = {};
    local posIndex = 1;
    for i = 1, totalNum do
        local child = widget:clone();
        child:setAnchorPoint(cc.p(0, 0));
        child:setPositionX(leftMargin);
        child:setPositionY(startHeight + totalHeight - posIndex * (widgetHeight + gap));
        child:setTag(i);
        child:setName("item"..i);

        local classId = i + 1000;

        if i == 1 or table.indexOf(ress, classId) ~= -1 then
            child:setVisible(true);
            posIndex = posIndex + 1;
        else
            child:setVisible(false);
        end

        -- 减少工人处理
        local btnSub = findChildByName(child, "btn_sub");
        btnSub:setTag(i);
        btnSub:addTouchEventListener(function(sender, eventType)
            -- 单次处理
            local function doSub()
                local type = sender:getTag();
                AudioM.playFx("button_click");
                if self.config[type] > 0 then
                    self.config[type] = self.config[type] - 1;
                    self.idleWorkerNum = self.idleWorkerNum + 1;

                    self:updateByType(type);

                    return true;
                end
                return false;
            end

            -- 长按处理
            local function longPressSub()
                local delay = 0.1;
                if doSub() then
                    self.autoCount = self.autoCount + 1;
                    if self.autoCount > 5 then
                        delay = delay / 2;
                    end
                    performWithDelay(sender, longPressSub, delay);
                end
            end

            if eventType == ccui.TouchEventType.began then
                self.autoCount = 0;
                performWithDelay(sender, longPressSub, 0.5);
            elseif eventType == ccui.TouchEventType.ended then
                sender:stopAllActions();
                doSub();
            elseif eventType == ccui.TouchEventType.canceled then
                sender:stopAllActions();
            end
        end);

        -- 增加工人处理
        local btnAdd = findChildByName(child, "btn_add");
        btnAdd:setTag(i);
        btnAdd:addTouchEventListener(function(sender, eventType)
            -- 单次处理
            local function doAdd()
                local type = sender:getTag();
                AudioM.playFx("button_click");
                if self.idleWorkerNum > 0 and self.config[type] < WorkerLimit then
                    self.config[type] = self.config[type] + 1;
                    self.idleWorkerNum = self.idleWorkerNum - 1;

                    self:updateByType(type);

                    EventMgr.fire(event.TARGET_CLICK, { object = sender, } );
                    return true;
                end
                return false;
            end

            -- 长按处理
            local function longPressAdd()
                local delay = 0.1;
                if doAdd() then
                    self.autoCount = self.autoCount + 1;
                    if self.autoCount > 5 then
                        delay = delay / 2;
                    end
                    performWithDelay(sender, longPressAdd, delay);
                end
            end

            if eventType == ccui.TouchEventType.began then
                self.autoCount = 0;
                performWithDelay(sender, longPressAdd, 0.5);
            elseif eventType == ccui.TouchEventType.ended then
                sender:stopAllActions();
                doAdd();
            elseif eventType == ccui.TouchEventType.canceled then
                sender:stopAllActions();
            end
        end);

        scrollview:addChild(child);
        self.workshopChildren[i] = child;
        table.insert(self.items, child);

        self:updateWorkshopItem(i);
    end

    local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
    if uiForm then
        uiForm:stopEffect();
        performWithDelay(self, function() uiForm:resumeEffect() end, 2);
    end

    if AlchemyWorkshopM.isAllGuideFinished() then
        commonScrollItemFlyIn(self.items);
        scrollview:setBounceEnabled(true);
        scrollview:scrollToTop(0.1, true);
    else
        -- 还在引导中，禁止滑动，防止出现无法点击的问题
        scrollview:setBounceEnabled(false);
    end

    UIMgr:getCurrentScene().topMenu:showWorkerInfo(self.totalWorkerNum, self.idleWorkerNum);
end

-- 更新工坊的外观
function UIWorkshopConfig:updateWorkshopItem(type)
    local child = self.workshopChildren[type];

    -- 图标
    local icon = findChildByName(child, "icon");
    icon:loadTexture("images/ui/workshop/icon/"..type..".png");

    -- 工人名称
    local workerNameLabel = findChildByName(child, "worker_name");
    local nameLabel = findChildByName(child, "name");
    local nameEnLabel = findChildByName(child, "name_en");
    local countLabel = findChildByName(child, "count");

    TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE, true);
    TextStyleM.setShadowStyle(countLabel, cc.size(-0.3, -2.8), TextStyleM.TEXT_COLOR_YELLOW_BROWN);
    TextStyleM.setOutlineStyle(countLabel, 1, TextStyleM.TEXT_OUTLINE_COLOR, true);

    TextStyleM.setTextStyle(workerNameLabel, 28, TextStyleM.TEXT_COLOR_BEIGE, true, -1, nil, nil, nil, nil, true);
    workerNameLabel:setString(workerNames[type]);
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, true, -1, nil, nil, nil, nil, true);
    TextStyleM.setTextStyle(nameEnLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, true, -2, nil, nil, nil, nil, true);

    TextStyleM.setShadowStyle(workerNameLabel, cc.size(-0.3, -2.8), TextStyleM.TEXT_COLOR_YELLOW_BROWN);
    TextStyleM.setOutlineStyle(workerNameLabel, 1, TextStyleM.TEXT_OUTLINE_COLOR, true);
    TextStyleM.setShadowStyle(nameLabel, cc.size(-0.3, -2.8), TextStyleM.TEXT_COLOR_YELLOW_BROWN);
    TextStyleM.setOutlineStyle(nameLabel, 1, TextStyleM.TEXT_OUTLINE_COLOR, true);
    TextStyleM.setShadowStyle(nameEnLabel, cc.size(-0.3, -2.8), TextStyleM.TEXT_COLOR_YELLOW_BROWN);
    TextStyleM.setOutlineStyle(nameEnLabel, 1, TextStyleM.TEXT_OUTLINE_COLOR, true);

    -- 设置自动换行
    nameEnLabel:getVirtualRenderer():setMaxLineWidth(6 * TextStyleM.TEXT_SIZE_SMALL);

    -- 如果是非中文版本，需要使用非中文版本的特殊显示
    -- 不显示工匠名称，产物信息居中显示
    if getLang() ~= "zh" and getLang() ~= "tw" then
        workerNameLabel:setVisible(false);
        nameLabel:setVisible(false);
        nameEnLabel:setVisible(true);
    else
        workerNameLabel:setVisible(true);
        nameLabel:setVisible(true);
        nameEnLabel:setVisible(false);
    end

    -- 更新数量
    self:updateCount(type);
end

-- 更新数量
function UIWorkshopConfig:updateCount(type)
    -- 起始道具ID
    local startItemId = 1001;
    local itemid = startItemId + type - 1;

    -- 每单位产出需要工人数
    local workerPerUnit = FormulaM.invoke("GET_ALCHEMY_WORKER_NUM_PER_UNIT", type);

    local child = self.workshopChildren[type];

    -- 名称
    local name = findChildByName(child, "name");
    local nameEn = findChildByName(child, "name_en");
    local nameTxt = ItemM.query(itemid, "name");
    if itemid == 1001 then
        nameTxt = getLocStr("money");
    end
    name:setString(nameTxt.." +"..self.config[type] / workerPerUnit);
    nameEn:setString(nameTxt.." +"..self.config[type] / workerPerUnit);

    -- 当前数量和转化数量
    local curNum = ItemM.getAmount(ME.user, itemid);
    local countLabel = findChildByName(child, "count");
    local ruleId = CompoundM.getAutoCompoundRule(itemid);
    local materialInfo = CompoundM.query(ruleId, "material");
    local ruleType = CompoundM.query(ruleId, "type");
    materialInfo = FormulaM.invoke("CALC_COMPOUND_MATERIAL", ME.user, materialInfo, ruleType);
    countLabel:setString(curNum.."/" .. materialInfo[itemid]);
    if itemid == 1001 then
        countLabel:setString("-/-");
        countLabel:setVisible(false);
    end

    -- 当前工坊的工人数量
    local curWorkerNum = self.config[type];

    if curWorkerNum == 0 then
        self:setGrayNode(child, true);
    else
        self:setGrayNode(child, false);
    end

    self:updateButton(type);
end

function UIWorkshopConfig:setGrayNode(node, flag)
    local bg = findChildByName(node, "bg");
    local bgMask = findChildByName(node, "bg_mask");
    local icon = findChildByName(node, "icon");
    local addIcon = findChildByName(node, "btn_add");
    local subIcon = findChildByName(node, "btn_sub");

    local nodeList = {bg, bgMask};
    for _, node in pairs(nodeList) do
        setGrayMode(node, flag);
    end

    setGrayTransMode(icon, flag);

    local opacity = flag and 180 or 255;
    addIcon:setOpacity(opacity);
    subIcon:setOpacity(opacity);
end

-- 更新按钮外观
function UIWorkshopConfig:updateButton(type)
    local workerPerUnit = FormulaM.invoke("GET_ALCHEMY_WORKER_NUM_PER_UNIT", type);
    local curWorkerNum = self.config[type];

    local child = self.workshopChildren[type];

    local btnSub = findChildByName(child, "btn_sub");
    local btnAdd = findChildByName(child, "btn_add");

    if curWorkerNum <= 0 then
        -- 工人数已经为0，无法再减少
        setButtonEnabled(btnSub, false);
        btnSub:stopAllActions();
    else
        setButtonEnabled(btnSub, true);
    end

    if self.idleWorkerNum < workerPerUnit or curWorkerNum >= WorkerLimit then
        -- 剩余工人数不足该工坊的"单位需求人数"，或者工人数量达到上限，无法增加
        setButtonEnabled(btnAdd, false);
        btnAdd:stopAllActions();
    else
        setButtonEnabled(btnAdd, true);
    end
end

-- 只更新数量
function UIWorkshopConfig:updateAllCount()
    for i = 1, totalNum do
        self:updateCount(i);
    end
end

-- 更新所有
function UIWorkshopConfig:updateByType(type)
    for i = 1, totalNum do
        if i == type then
            self:updateCount(i);
        else
            self:updateButton(i);
        end
    end

    UIMgr:getCurrentScene().topMenu:showWorkerInfo(self.totalWorkerNum, self.idleWorkerNum);
end

resize = function(self)
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local scale = math.min(w / DESIGN_WIDTH, h / DESIGN_HEIGHT);

    -- 设置scroll的新视口高度
    local scrollview = findChildByName(self.node, "TOP/scrollview");
    local scrollViewSize = scrollview:getContentSize();

    local height = (h / scale) - 410;
    scrollview:setContentSize(scrollViewSize.width, height);
    scrollview:setInnerContainerSize(cc.size(scrollViewSize.width, height));

    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- TOP置于顶部中间并缩放至合适大小
    AlignM.alignToTopCenter(node, "TOP");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end


